<!-- 表格组件 -->
<script lang="tsx" setup>
import type { TableInstance } from 'element-plus';

import type { TableColumnOption } from '@/components/table-widget/table-widget.vue';
import {
  COMMITMENT_LEVEL_OPTIONS,
  COMMITMENT_TYPE_OPTIONS,
  getEnumOptionsField,
} from '@/config/enum-options';
import type { components } from '@/genapi/wh';
import { whManagerBsTbCommitmentDeleteByIdIdUsingPost } from '@/genapi/wh';

import { injectState } from '../state';
import DetailDialog from './detail-dialog.vue';

defineOptions({ name: 'Sheet' });

const {
  page: { records, isLoading, execute },
} = injectState()!;

const detailDialogRef = shallowRef<InstanceType<typeof DetailDialog>>();

const tableRef = shallowRef<TableInstance>();

watch(records, () => tableRef.value?.clearSelection());

const onDelete = async (row: (typeof records.value)[0]) => {
  console.log(row)
  await ElMessageBox.confirm(
    `您即将删除【${row.name ?? '未知'}】，删除后不可恢复，是否确认删除？`,
    '提示',
    {
      type: 'error',
    },
  );
  await whManagerBsTbCommitmentDeleteByIdIdUsingPost({ path: { id: row.id! } });
  ElMessage.success('删除成功');
  await execute();
};

const columns: TableColumnOption<components['schemas']['TbCommitmentDuiXiang']>[] = [
  {
    label: '序号',
    type: 'index',
    fixed: 'left',
    width: 80,
  },
  {
    label: '承诺类别',
    formatter(row) {
      return getEnumOptionsField(COMMITMENT_TYPE_OPTIONS, 'label', row.type, '-');
    },
  },
  {
    label: '承诺详情',
    prop: 'commitDesc',
  },
  {
    label: '安全风险等级',
    formatter(row) {
      return getEnumOptionsField(COMMITMENT_LEVEL_OPTIONS, 'label', row.level, '-');
    },
  },
  {
    label: '创建时间',
    prop: 'createTime',
  },
  {
    label: '承诺期限',
    formatter(row) {
      return `${row.commitStartDate}-${row.commitEndDate}`;
    },
  },
  {
    label: '操作',
    export: false,
    fixed: 'right',
    width: '200',
    formatter(row) {
      return (
        <>
          <el-button
            size="small"
            type="primary"
            text
            onClick={() => detailDialogRef.value?.trigger('read', row)}
          >
            详情
          </el-button>
          <el-button
            size="small"
            type="primary"
            text
            onClick={() => detailDialogRef.value?.trigger('write', row)}
          >
            编辑
          </el-button>
          <el-button size="small" type="primary" text onClick={() => onDelete(row)}>
            删除
          </el-button>
        </>
      );
    },
  },
];
</script>

<template>
  <TableWidget v-loading="isLoading" :data="records" :columns="columns" h="100%!" />

  <DetailDialog ref="detailDialogRef" />
</template>
